package sign

import (
	"sweetsunnyflower/pkg/app"
	"sweetsunnyflower/pkg/database"
	"sweetsunnyflower/pkg/paginator"

	"github.com/golang-module/carbon/v2"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func Get(idstr string) (sign Sign) {
	database.DB.Where("id", idstr).First(&sign)
	return
}

func GetBy(field, value string) (sign Sign) {
	database.DB.Where("? = ?", field, value).First(&sign)
	return
}

func All() (signs []Sign) {
	database.DB.Find(&signs)
	return
}

func IsExist(field, value string) bool {
	var count int64
	database.DB.Model(Sign{}).Where("? = ?", field, value).Count(&count)
	return count > 0
}

func Paginate(c *gin.Context, perPage int) (signs []Sign, paging paginator.Paging) {
	paging = paginator.Paginate(
		c,
		database.DB.Model(Sign{}),
		&signs,
		app.V1URL(database.TableName(&Sign{})),
		perPage,
	)
	return
}

// GetSignsOfWeek 用户本周签到记录
func GetSignsOfWeek(userID uint64) (signs []*Sign, err error) {

	startTime := carbon.Now().StartOfWeek().ToDateTimeString()

	endTime := carbon.Now().EndOfWeek().ToDateTimeString()

	err = database.DB.Where("user_id = ?", userID).
		Where("created_at >= ?", startTime).
		Where("created_at <= ?", endTime).
		Find(&signs).Error

	if err != nil {
		return nil, err
	}

	return signs, nil
}

// IsSignToday
func IsSignToday(userID uint64) (isSign bool, sign *Sign, err error) {

	startTime := carbon.Now().StartOfDay().ToDateTimeString()

	endTime := carbon.Now().EndOfDay().ToDateTimeString()

	err = database.DB.Where("user_id = ?", userID).
		Where("created_at >= ?", startTime).
		Where("created_at <= ?", endTime).
		First(&sign).Error

	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return false, nil, nil
		} else {
			return false, nil, err
		}
	}

	return true, sign, nil
}
